package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.service.CartInfoService;
import com.atguigu.gmall.common.result.Result;
import com.atguigu.gmall.common.util.AuthContextHolder;
import com.atguigu.gmall.model.cart.CartInfo;
import lombok.RequiredArgsConstructor;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;

/**
 * @author Fxz
 * @version 1.0
 * @date 2022-02-16 16:24
 */
@SuppressWarnings("all")
@RestController
@RequiredArgsConstructor
@RequestMapping("/api/cart")
public class CartApiController {

	private final CartInfoService cartInfoService;

	/**
	 * 添加购物车
	 */
	@PostMapping("/addToCart/{skuId}/{skuNum}")
	public Result addToCart(@PathVariable("skuId") Long skuId, @PathVariable("skuNum") Integer skuNum,
			HttpServletRequest request) {
		String userId = AuthContextHolder.getUserId(request);
		if (StringUtils.isEmpty(userId)) {
			userId = AuthContextHolder.getUserTempId(request);
		}
		cartInfoService.addToCart(skuId, userId, skuNum);
		return Result.ok();
	}

	/**
	 * 查询购物车列表
	 */
	@GetMapping("/cartList")
	public Result cartList(HttpServletRequest request) {
		return Result.ok(cartInfoService.getCartList(AuthContextHolder.getUserId(request),
				AuthContextHolder.getUserTempId(request)));
	}

	/**
	 * 更新选中状态
	 */
	@GetMapping("/checkCart/{skuId}/{isChecked}")
	public Result checkCart(@PathVariable("skuId") Long skuId, @PathVariable("isChecked") Integer isChecked,
			HttpServletRequest request) {
		String userId = AuthContextHolder.getUserId(request);
		if (StringUtils.isEmpty(userId)) {
			userId = AuthContextHolder.getUserTempId(request);
		}
		cartInfoService.checkCart(userId, isChecked, skuId);
		return Result.ok();
	}

	@GetMapping("/getCartCheckedList/{userId}")
	public List<CartInfo> getCartCheckedList(@PathVariable("userId") Long userId) {
		return cartInfoService.getCartCheckedList(userId);
	}

	/**
	 * 删除购物项
	 */
	@DeleteMapping("/deleteCart/{skuId}")
	public Result deleteCart(@PathVariable("skuId") Long skuId, HttpServletRequest request) {
		String userId = AuthContextHolder.getUserId(request);
		if (StringUtils.isEmpty(userId)) {
			userId = AuthContextHolder.getUserTempId(request);
		}
		cartInfoService.deleteCartInfo(userId, skuId);
		return Result.ok();
	}

	/**
	 * 跟据userId 加载购物车实时价格
	 */
	@GetMapping("/loadCartCache/{userId}")
	Result loadCartCache(@PathVariable("userId") String userId) {
		return Result.ok(cartInfoService.loadCartCache(userId));
	}

}
